package com.cicadasmall.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cicadasmall.common.base.BaseService;
import com.cicadasmall.data.domain.DeptDO;
import com.cicadasmall.data.domain.UserDeptDO;
import com.cicadasmall.data.mapper.SysUserDeptMapper;
import com.cicadasmall.system.service.IDeptService;
import com.cicadasmall.system.service.IUserDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 用户部门关联表 service impl class
 * </p>
 *
 * @author westboy
 * @date 2019-08-21
 */
@Service
public class UserDeptServiceImpl extends BaseService<SysUserDeptMapper, UserDeptDO> implements IUserDeptService {
    @Autowired
    private IDeptService deptService;


    @Override
    public List<UserDeptDO> findByUserId(Serializable uid) {
        return baseMapper.selectList(getLambdaQueryWrapper().eq(UserDeptDO::getUid,uid));
    }


    @Override
    public void updateUserDept(Integer uid, List<String> deptIds) {
        if(CollectionUtil.isNotEmpty(deptIds)){
            LambdaQueryWrapper lambdaQueryWrapper = getLambdaQueryWrapper().eq(UserDeptDO::getUid,uid);
            Integer count = baseMapper.selectCount(lambdaQueryWrapper);

            if(count>0){
                baseMapper.delete(lambdaQueryWrapper);
            }

            deptIds.forEach(deptId->{
                DeptDO dept =  deptService.getById(deptId);
                if(dept!=null){
                    UserDeptDO userDept = new UserDeptDO();
                    userDept.setDeptId(dept.getDeptId());
                    userDept.setUid(uid);
                    baseMapper.insert(userDept);
                }
            });
        }
    }
}
